package com.wstuo.common.security.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.bpm.api.IBPS;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.dao.ICompanyDAO;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IResourceDAO;
import com.wstuo.common.security.dao.IRoleDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dao.UserDAO;
import com.wstuo.common.security.dto.CompanyDTO;
import com.wstuo.common.security.dto.EditUserPasswordDTO;
import com.wstuo.common.security.dto.LDAPAuthenticationSettingDTO;
import com.wstuo.common.security.dto.LDAPDTO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.dto.RoleDTO;
import com.wstuo.common.security.dto.UserDTO;
import com.wstuo.common.security.dto.UserDetailDTO;
import com.wstuo.common.security.dto.UserGridDTO;
import com.wstuo.common.security.dto.UserQueryDTO;
import com.wstuo.common.security.dto.UserRoleDTO;
import com.wstuo.common.security.entity.Company;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.Resource;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.TechnicalGroup;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.entity.UserInfoClient;
import com.wstuo.common.security.enums.SessionName;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.sha.JDKMessageDigest;
import com.wstuo.common.sso.dto.SSOUserDTO;
import com.wstuo.common.util.AppliactionBaseListener;
import com.wstuo.common.util.StringUtils;

/**
 * 用户业务Services
 */
public class UserInfoService implements IUserInfoService{
	private static final Logger LOGGER = Logger
			.getLogger(UserInfoService.class);
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private IRoleDAO roleDAO;
	@Autowired
	private ILDAPAuthenticationSettingService ldapAuthenticationSettingService;
	@Autowired
	private ILDAPService ldapService;
	@Autowired
	private ICompanyDAO companyDAO;
	@Autowired
	private AppContext appctx;
	@Autowired
	private IResourceDAO resourceDAO;
	
	@Autowired
	private IOrganizationService organizationService; 
	private JDKMessageDigest sha = new JDKMessageDigest();
	public static final String SAVE_JBPMUSER="save"; 
	public static final String MODIFY_JBPMUSER="modify";
	/**
	 * getRoleByRoleCode
	 * @param roleCode
	 * @return Role
	 */
	private Role getRoleByRoleCode(String roleCode){
		Role role =roleDAO.findUniqueBy("roleCode", roleCode);
		return role;
	}

	/**
	 * getRoleByIds(String[] roleIds)
	 * 
	 * @param roleIds
	 * @return Set<Role>
	 */
	public Set<Role> getRoleByIds(Long[] roleIds) {
		Set<Role> roles = new HashSet<Role>();
		if (roleIds != null) {
			for (Long roleId : roleIds) {
				Role role = roleService.findRoleById(roleId);
				roles.add(role);
			}
		}
		return roles;
	}
	/**
	 * 设置JBPM用户和组的属性值
	 * @param org
	 * @param roles
	 * @param user
	 */
	@Transactional
	private void setJBPMUser(Organization org,Set<Role> roles,User user,String method){
		ApplicationContext ctx = AppliactionBaseListener.ctx;
		if (ctx != null) {
			IBPS bps = (IBPS) ctx.getBean("bps");
			if(SAVE_JBPMUSER.equals(method)){
				// 创建JBPM用户
				bps.createUser(user.getLoginName(), user.getFirstName(),
						user.getLastName(), user.getEmail());
			}else{
				bps.modifyUser(user.getLoginName(), user.getFirstName(),
						user.getLastName(), user.getEmail());
			}
			// 添加用户与组的关系
			if(org!=null){
				Organization parentOrg = org.getParentOrg();
				if (parentOrg != null){
					bps.createMembership("Group_" + org.getOrgNo(), "Group_"
							+ parentOrg.getOrgNo(),
							new String[] { user.getLoginName() });
				}else{
					bps.createMembership("Group_" + org.getOrgNo(), null,
							new String[] { user.getLoginName() });
				}
			}
			// 修改技术组关系
			Set<Organization> belongsGroups = user.getBelongsGroup();
			if (belongsGroups != null ) {
				for (Organization bg : belongsGroups) {
					bps.createMembership("Group_" + bg.getOrgNo(), "Group_"
							+ bg.getOrgNo(),
							new String[] { user.getLoginName() });
				}
			}
			// 添加用户与角色的关系
			if(roles != null){
				for (Role role : roles) {
					bps.createMembership(role.getRoleCode(), null,
							new String[] { user.getLoginName() });
				}
			}
		}
	}

	/**
	 * 保存用户信息.
	 * @param userDto 数据DTO：UserDTO
	 */
	@Transactional
	public void saveUser(UserDTO userDto) {
		
		User user = userDAO.findUserByLoginName(userDto.getLoginName());
		if(user==null){
			user = new User();
			UserDTO.dto2entity(userDto, user);
			user.setCreateTime(new Date());
			//属性转换
			dto2entity(userDto, user);
			Set<Role> roles = new HashSet<Role>();
			if(userDto.getRoleIds()!=null){
				roles.addAll(getRoleByIds(userDto.getRoleIds()));
			}else{
				Role role = roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_ENDUSER);
				roles.add(role);
			}
			if(userDto.getRoleCode()!=null){
				Role rl = getRoleByRoleCode(userDto.getRoleCode());
				roles.add(rl);
			}
			user.setRoles(roles);
			userDAO.save(user);
			userDto.setUserId(user.getUserId());
			//设置JBPM用户和组的属性值
			setJBPMUser(user.getOrgnization(), roles, user,SAVE_JBPMUSER);
		}else{
			userDto.setUserId(user.getUserId());
			editUser(userDto);
		}
	}

	/**
	 * dto to entity
	 */
	@Transactional
	private void dto2entity(UserDTO userDto ,User user){
		user.setFullName("");
		Organization org = organizationDAO.findById(userDto.getOrgNo());
		user.setOrgnization(org);
		// 属性组
		if (userDto.getBelongsGroupIds() != null) {
			Set<Organization> belongsGroups = new HashSet<Organization>();
			for (Long groupId : userDto.getBelongsGroupIds()) {
				Organization group = organizationDAO.findById(groupId);
				belongsGroups.add(group);
			}
			user.setBelongsGroup(belongsGroups);
		}else{
			user.setBelongsGroup(null);
		}
	}
	/**
	 * edit user
	 * 
	 * @param userDto
	 */
	@Transactional
	public void editUser(UserDTO userDto) {
		User user = userDAO.findById(userDto.getUserId());
		userDto.setPassword(user.getPassword());
		if(userDto.getRoleIds() == null){
			Long[] roleIds = new Long[user.getRoles().size()];
			int i =0;
			for (Role role : user.getRoles()) {
				roleIds[i] = role.getRoleId();
				i++;
			}
			userDto.setRoleIds(roleIds);
		}
		UserDTO.dto2entity(userDto, user);
		Set<Role> roles = getRoleByIds(userDto.getRoleIds());
		user.setLastUpdateTime(new Date());
		Boolean oldState = user.getUserState();
		boolean countTc = false;
		if (userDAO.isTc(roles)) {//要分配技术员的角色
			if (user.getUserId() !=null&&user.getUserId() != 0) {// 修改数据
				Set<Role> rolesOld = new HashSet<Role>(
						roleDAO.findByUserId(user.getUserId()));
				if (!userDAO.isTc(rolesOld)) {
					countTc = true;
				}
			} else {// 新增数据
				countTc = true;
			}
		}
		user.setRoles(roles);
		if (countTc && userDto.getUserState() 
				&& !oldState
				&& roles != null
				&& userDAO.isTc(roles)
				&& UserDAO.licenseNumber - countTechnician() < 1) {// 启用用户
			throw new ApplicationException("TechnicianLicense_Not_Enough");
		}
		//属性转换
		dto2entity(userDto, user);
		userDAO.merge(user);
		//设置JBPM用户和组的属性值
		setJBPMUser(user.getOrgnization(), roles, user,MODIFY_JBPMUSER);
	}

	/**
	 * query user
	 * 
	 * @param userQueryDto
	 * @param sord
	 * @param sidx
	 * @return PageDTO
	 */
	@SuppressWarnings("unchecked")
    @Transactional
	public PageDTO findPagerUser(UserQueryDTO userQueryDto, String sord,
			String sidx) {
		if (!selectCurrentUserRole()) {
			userQueryDto.setUserState(true);
		}
		searchOrganization(userQueryDto);
		PageDTO p = userDAO.findPager(userQueryDto, sord, sidx);
		List<User> entities = (List<User>) p.getData();
		List<UserGridDTO> dtos = new ArrayList<UserGridDTO>(entities.size());
		for (User entity : entities) {
			UserGridDTO gridDTO = new UserGridDTO();
			gridDTO.entity2dto(entity, gridDTO);
			//属性转换
			entity2dto(entity, gridDTO);
			dtos.add(gridDTO);
		}
		p.setData(dtos);
		return p;
	}
	
	/**
	 * entity to dto
	 */
	@SuppressWarnings("unchecked")
	private void entity2dto(User entity,UserGridDTO gridDTO){
		if (entity.getOrgnization() != null) {
			gridDTO.setOrgName(entity.getOrgnization().getOrgName());
		}
		if (entity.getRoles() != null && entity.getRoles().size() > 0) {
			StringBuffer roles = new StringBuffer();
			List<Role> listRole = new ArrayList<Role>();
			for (Role role : entity.getRoles()) {
				listRole.add(role);
			}
			ComparatorRole comparator = new ComparatorRole();
			Collections.sort(listRole, comparator);
			for (Role role : listRole) {
				if (role.getDataFlag() != 99) {
					if (roles!=null&&StringUtils.hasText(roles.toString())) {
						roles.append("," + role.getRoleName());
					} else {
						roles.append(role.getRoleName());
					}
				}
			}
			gridDTO.setRoles(roles.toString());
		} else {
			gridDTO.setRoles("");
		}
		// 技术组
		if (entity.getTcGroup() != null && entity.getTcGroup().size() > 0) {
			String[] groupNames = new String[entity.getTcGroup().size()];
			Long[] groupIds = new Long[entity.getTcGroup().size()];
			int z = 0;
			for (TechnicalGroup tg : entity.getTcGroup()) {
				groupNames[z] = tg.getTechnicalGroupName();
				groupIds[z] = tg.getTechnicalGroupId();
				z++;
			}
			gridDTO.setTcGroupNames(groupNames);
			gridDTO.setTcGroupIds(groupIds);
		}
		// 所属组
		if (entity.getBelongsGroup() != null) {
			StringBuffer sb = new StringBuffer();
			for (Organization org : entity.getBelongsGroup()) {
				sb.append(org.getOrgName() + ",");
			}
			gridDTO.setBelongsGroupStr(sb.toString());
		}
	}

	private boolean selectCurrentUserRole() {
		boolean result = false;
		UserDTO user = this.getCurrentLoginUser();
		if(user!=null){
			for (RoleDTO role : user.getUserRoles()) {
				if (IRoleService.ROLE_SYSADMIN.equals(role.getRoleCode())) {
					result = true;
					break;
				}
			}
		}
		return result;
	}

	/**
	 * delete user
	 * 
	 * @param userId
	 * @return boolean
	 */
	@Transactional
	public boolean delUser(Long[] userId) {
		boolean result = true;
		Byte delete = 1;
		for (Long id : userId) {
			User user = userDAO.findById(id);
			if (user.getDataFlag().equals(delete)) {
				result = false;
			}
		}
		if (result) {
			userDAO.deleteByIds(userId);
		}
		return result;
	}

	/**
	 * 批量修改用户角色
	 * @param ids
	 * @param roleIds
	 */
	@Transactional
	public void mergeAllUser(Long[] ids, Long[] roleIds) {
		if (ids != null && ids.length > 0) {
			for (Long id : ids) {
				User user = findUserById(id);
				Set<Role> roleSet = new HashSet<Role>();
				if (roleIds != null && roleIds.length > 0) {
					for (Long roleId : roleIds) {
						Role role = roleService.findRoleById(roleId);
						roleSet.add(role);
					}
				}
				//user.setRoles(roleSet);
				user.setLastUpdateTime(new Date());
				userDAO.mergeByRoles(user,roleSet);
			}
		} else {
			throw new ApplicationException("批量设置用户角色时出问题，用户编号为空！");
		}
	}

	/**
	 * List<User> findAll()
	 * 
	 * @return List<User>
	 */
	public List<User> findAllUser() {
		List<User> list;
		list = userDAO.findAll();
		return list;
	}

	/**
	 * findById(long id)
	 * 
	 * @param id
	 * @return User
	 */
	@Transactional
	public User findUserById(long id) {
		return userDAO.findById(id);
	}

	/**
	 * getUserRole(long id)
	 * 
	 * @param id
	 * @return List<UserRoleDTO>
	 */
	@Transactional
	public List<UserRoleDTO> getUserRoleByUserId(long id) {
		List<UserRoleDTO> list = new ArrayList<UserRoleDTO>();
		User user = userDAO.findById(id);
		Set<Role> roleSet = user.getRoles();
		Iterator<Role> iterator = roleSet.iterator();
		while (iterator.hasNext()) {
			UserRoleDTO userRoleDto = new UserRoleDTO();
			Role role1 = iterator.next();
			userRoleDto.setRoleId(role1.getRoleId());
			userRoleDto.setRoleName(role1.getRoleName());
			list.add(userRoleDto);
		}

		return list;
	}

	/**
	 * user is Exist
	 * 
	 * @param loginName
	 * @return boolean
	 */
	public boolean userExist(String loginName) {
		User user = userDAO.findUniqueBy("loginName", loginName);
		boolean result = true;
		if (user != null) {
			result = false;
		}
		return result;
	}

	/**
	 * 自动补全验证用户
	 */
	public Set<Long> autoVerification(String fullName) {
		List<User> list = userDAO.findBy("fullName", fullName);
		List<User> list1 = userDAO.findBy("loginName", fullName);
		Set<Long> set = new HashSet<Long>();
		if (list != null) {
			for (int j = 0; j < list.size(); j++) {
				set.add(list.get(j).getUserId());
			}
		}
		if (list1 != null) {
			for (int j = 0; j < list1.size(); j++) {
				set.add(list1.get(j).getUserId());
			}
		}
		return set;
	}

	/**
	 * mergeByOrg
	 * 
	 * @param ids
	 * @param orgNo
	 * @return boolean
	 */
	@Transactional
	public boolean mergeByOrg(String str, long orgNo) {
		boolean result = false;
		String[] ids =null;
		if (str != null && !str.equals("")) {
			ids = str.split(",");
		}
		if (ids != null) {
			List<User> users = new ArrayList<User>();
			Organization org = organizationDAO.findById(orgNo);
			for (int i = 0; i < ids.length; i++) {
				User user = findUserById(Integer.parseInt(ids[i]));
				user.setOrgnization(org);
				users.add(user);
				//设置JBPM用户和组的属性值
				setJBPMUser(org, null, user, MODIFY_JBPMUSER);
			}
			try {
				userDAO.mergeAll(users);
				result = true;
			} catch (Exception e) {
				LOGGER.error(e);
				result = false;
			}
		}
		return result;
	}

	/**
	 * findUserByName
	 * 
	 * @param uname
	 * @return UserDTO
	 */
	@Transactional
	public UserDTO findUserByName(String uname) {
		User user = userDAO.findUniqueBy("loginName", uname);
		UserDTO dto = null;
		if (user != null) {
			dto = new UserDTO();
			dto.setLoginName(uname);
			UserDTO.entity2dto(user, dto);
			if (user.getBelongsGroup() != null) {
				StringBuffer sb = new StringBuffer();
				Long[] bgIds = new Long[user.getBelongsGroup().size()];
				int i = 0;
				for (Organization org : user.getBelongsGroup()) {
					sb.append(org.getOrgName() + ",");
					bgIds[i] = org.getOrgNo();
					i++;
				}
				dto.setBelongsGroup(sb.toString());
				dto.setBelongsGroupIds(bgIds);
			}
			if(user.getOrgnization()!=null){
				dto.setOrgNo(user.getOrgnization().getOrgNo());
				dto.setOrgName(user.getOrgnization().getOrgName());
			}
		}
		return dto;
	}

	/**
	 * findUserByName
	 * @param fullNames
	 * @return boolean
	 */
	@Transactional
	public Boolean findUserByFullNames(String[] fullNames) {
		boolean result = true;
		if (fullNames != null && fullNames.length > 0) {
			for (String name : fullNames) {
				if (userDAO.findByUserFullNames(name) == false) {
					result = false;
					break;
				}
			}
		}
		return result;
	}

	/**
	 * findDisable
	 * 
	 * @param uname
	 * @param pwd
	 * @return String
	 */
	@Transactional
	public String findDisable(String uname, String pwd) {
		return userDAO.findDisable(uname, pwd);
	}


	/**
	 * 导出数据方法
	 * 
	 * @throws Exception
	 */
    @Transactional
	public InputStream exportUserItems(UserQueryDTO userQueryDTO, String sord,
			String sidx) {
		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		LanguageContent lc = LanguageContent.getInstance();
		List<String[]> data = new ArrayList<String[]>();
		data.add(new String[] {
				lc.getContent("label.basicSettings.serviceLoginName"),
				lc.getContent("label.user.userFirstName"),
				lc.getContent("label.user.userLastName"),
				lc.getContent("label.orgSettings.orgName"),
				lc.getContent("title.orgSettings.role"),
				lc.getContent("label.role.roleState"),
				lc.getContent("label.e-mail"),
				lc.getContent("label.telephone"),
				lc.getContent("label.mobile"), lc.getContent("label.fax"),
				"QQ/MSN", lc.getContent("label.user.workAddress"),
				lc.getContent("label.user.costEngineer"),
				lc.getContent("title.user.userRole"),
				lc.getContent("label.report.company"),
				lc.getContent("label.user.holidayStatus") });
		searchOrganization(userQueryDTO);
		List<User> entities = userDAO.findUserList(userQueryDTO, sord, sidx);
		for (User user : entities) {
			String status = lc.getContent("common.disable");
			String orgName = "";
			StringBuffer roles = new StringBuffer();
			// String password="";
			String CompanyName = "";
			String holidayStatus = "";
			if (user.getUserState()) {
				status = lc.getContent("common.enable");
			}
			if (user.getRoles() != null && user.getRoles().size() > 0) {
				for (Role role : user.getRoles()) {
					roles.append(role.getRoleName() + "("
							+ role.getRoleCode() + "),");
				}
			}
			if (user.getOrgnization() != null) {
				orgName = user.getOrgnization().getOrgName();
				CompanyName = user.getOrgnization().getOrgName();
			}
			if (user.getHolidayStatus()) {
				holidayStatus = lc.getContent("label.user.holiday.ing");
			} else {
				holidayStatus = lc.getContent("label.user.duty.ing");
			}
			data.add(new String[] {
					user.getLoginName(),
					// password,
					user.getLastName(), user.getFirstName(), orgName,
					user.getJob(), status, user.getEmail(),
					user.getPhone(), user.getMoblie(), user.getFax(),
					user.getMsn(), user.getOfficeAddress(),
					user.getUserCost() + "", roles.toString(), CompanyName,
					holidayStatus });
		}
		csvw.writeAll(data);
		
		
		byte[] bs = null;
		try {
			bs = sw.getBuffer().toString().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		ByteArrayInputStream stream = null;
		if(bs!=null){
			stream = new ByteArrayInputStream(bs);
		}
		try {
        	if(csvw!=null){
        		csvw.flush();
    			csvw.close();
        	}
			if(sw!=null){
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;

	}

	// 查询子机构
    @SuppressWarnings("rawtypes")
	private void searchOrganization(UserQueryDTO userQueryDTO) {
		// 查找子机构
		if (userQueryDTO.getOrgNo() != null && userQueryDTO.getOrgNo() > 0) {
			Organization org  = organizationDAO.findById(userQueryDTO.getOrgNo());
			List list = organizationDAO.findOrgChildsIdsByPath(org.getPath());
			if(list.size()>0){
				Long[] orgsArr = new Long[list.size()];
				for (int i = 0; i < list.size(); i++) {
					orgsArr[i] = (Long) list.get(i);
				}
				userQueryDTO.setOrgNos(orgsArr);
			}
		}
	}

	/**
	 * 导入数据方法.
	 * @param importFile
	 * @return String
	 */
    @Transactional
	public String importUserItems(File importFile) {
    	ApplicationContext act = AppliactionBaseListener.ctx;
    	String lang="zh_CN";
    	if(act!=null){
			AppContext appctx = (AppContext) act.getBean("appctx");
			lang=appctx.getCurrentLanguage();//获取运用的语言
    	}
		String result = "";
		int insert = 0;
		int update = 0;
		int total = 0;
		int failure = 0;
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(importFile);
			Reader rd = new InputStreamReader(new FileInputStream(importFile),fileEncode);//以字节流方式读取数据
			CSVReader reader = new CSVReader(rd);
			String[] line = null;
			try {

				while ((line = reader.readNext()) != null) {
					String opt = "save";
					User user = userDAO.findUniqueBy("loginName",
							line[0].toString());
					boolean status = false;
					float userCost = 0;
					if (user == null) {
						user = new User();
						insert++;
					} else {
						opt = "update";
						update++;
					}
				
					user.setLoginName(trim(line[0].toString()));
					user.setPassword(trim(line[1].toString()));
					if("en_US".equals(lang)){
						user.setFirstName(trim(line[3].toString()));
						user.setLastName(trim(line[2].toString()));
						user.setFullName(line[3].toString() + ""
								+ line[2].toString());
					}else{
						user.setFirstName(trim(line[2].toString()));
						user.setLastName(trim(line[3].toString()));
						user.setFullName(line[2].toString() + ""
								+ line[3].toString());
					}
					
					if (line[4].toString() != null
							&& !line[4].toString().equals("")) {
						Organization org = organizationDAO.findById(Long
								.parseLong(line[4].toString()));
						if (org != null) {
							user.setOrgnization(org);
						}
					}
					user.setJob(line[5].toString());
					if (line[6].toString().equals("true")
							|| line[6].toString().equals("TRUE")) {
						status = true;
					}
					user.setUserState(status);
					user.setEmail(line[7].toString());
					user.setPhone(line[8].toString());
					user.setMoblie(line[9].toString());
					user.setFax(line[10].toString());
					user.setMsn(line[11].toString());
					user.setOfficeAddress(line[12].toString());

					if (line[13].toString() != null
							&& !line[13].toString().equals("")) {
						userCost = Float.parseFloat(line[13].toString());
					}
					user.setUserCost(userCost);
					//user.setRoles(StringConversionRoleSet(line[14].toString()));
					if (line[15] != null) {
						Company company = companyDAO.findUniqueBy("orgName",
								line[15].toString());
						if (company != null && ("company".equals(company.getOrgType()) || "itsop".equals(company.getOrgType()))){
							user.setCompanyNo(company.getOrgNo());
						}else{
							result = "ERROR_COMPANY_NAME";
							break;
						}
					}
					user.setBelongsGroup(StringConversionOrganizationSet(line[16]
							.toString()));
					userDAO.mergeByRoles(user, StringConversionRoleSet(line[14].toString()));
					setJBPMUser(user.getOrgnization(), user.getRoles(), user, opt);
					total++;
				}
				if(result == ""){
					result = "Total:" + total + ",&nbsp;Insert:" + insert
						+ ",&nbsp;Update:" + update + ",&nbsp;Failure:"
						+ failure;
				}
			} catch (IOException e) {
				LOGGER.error(e.getMessage());
				result = "IOError";
			} catch (ApplicationException ex) {
				LOGGER.error(ex.getMessage());
				result = "TCNotEnough";
			}

		} catch (Exception e1) {
			LOGGER.error(e1.getMessage());
			result = "FileNotFound";
		}
		return result;
	}

	// 根据字段串转成Set<Organization>
	private Set<Organization> StringConversionOrganizationSet(
			String OrganizationStr) {
		Set<Organization> orgs = new HashSet<Organization>();
		if (StringUtils.hasText(OrganizationStr)) {
			String[] OrganizationStrArray = OrganizationStr.split(",");
			if (OrganizationStrArray != null && OrganizationStrArray.length > 0) {
				for (String orgid : OrganizationStrArray) {
					if (StringUtils.hasText(orgid)) {
						Organization org = organizationDAO.findById(Long
								.parseLong(orgid));
						if (org != null) {
							orgs.add(org);
						}
					}
				}
			}
		}
		return orgs;
	}

	private static String trim(String s) {
		int i = s.length();// 字符串最后一个字符的位置
		int j = 0;// 字符串第一个字符
		int k = 0;// 中间变量
		char[] arrayOfChar = s.toCharArray();// 将字符串转换成字符数组
		while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
			++j;// 确定字符串前面的空格数
		while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
			--i;// 确定字符串后面的空格数
		return (((j > 0) || (i < s.length())) ? s.substring(j, i) : s);// 返回去除空格后的字符串
	}

	// 根据字段串转成Set<Role>
	private Set<Role> StringConversionRoleSet(String roleStr) {
		Set<Role> roles = new HashSet<Role>();
		if (StringUtils.hasText(roleStr)) {
			String[] roleArray = roleStr.split(",");
			if (roleArray != null && roleArray.length > 0) {
				for (String roleCode : roleArray) {
					if (StringUtils.hasText(roleCode)) {
						Role role = roleDAO.findUniqueBy("roleCode", roleCode);
						if (role != null) {
							roles.add(role);
						}
					}
				}
			}
		}
		return roles;

	}

	/**
	 * 修改用户密码
	 * 
	 * @param dto
	 * @return boolean
	 */
	@Transactional
	public boolean resetPassword(EditUserPasswordDTO dto) {
		boolean result = true;
		if (dto != null && dto.getLoginName() != null) {
			User user = userDAO.findUniqueBy("loginName", dto.getLoginName());
			if(user==null){
				user = userDAO.findUniqueBy("moblie", dto.getLoginName());
			}
			if (dto.getResetPassword() != null
					&& dto.getResetPassword().equals("resetPassword")) {
				user.setPassword("itsmbest");
			} else {
				if (!user.getPassword().equals(dto.getOldPassword())) {
					JDKMessageDigest sha = new JDKMessageDigest();
					if (dto.getOldPassword().equals(sha.Encryption("EditPassword"))){
						user.setPassword(dto.getNewPassword());
					}else{
						result = false;
					}
				} else {
					user.setPassword(dto.getNewPassword());
				}
			}
			if (result) {
				userDAO.merge(user);
			}
		}
		return result;
	}

	/**
	 * 根据ID获取UserDTO
	 * @param id long id
	 * @return UserDTO
	 */
	@Transactional
	public UserDTO findById(Long id) {
		UserDTO dto = new UserDTO();
		User entity = userDAO.findById(id);
		UserDTO.entity2dto(entity, dto);
		if (entity!=null&&entity.getRoles() != null) {
			int i = 0;
			Long[] roleIds = new Long[entity.getRoles().size()];
			for (Role role : entity.getRoles()) {
				roleIds[i] = role.getRoleId();
				i++;
			}
			dto.setRoleIds(roleIds);
		}
		if (entity!=null&&entity.getOrgnization() != null) {
			dto.setOrgNo(entity.getOrgnization().getOrgNo());
		}

		return dto;
	}

	/**
	 * 根据用户密码查看用户是否存在.
	 */
	@Transactional
	public Boolean findUserByPassword(String password) {
		List<User> ulist = userDAO.findBy("password", password);
		return (ulist != null && ulist.size() > 0);

	}

	/**
	 * 用户登录.
	 * 
	 * @param userName
	 * @param password
	 */
	@Transactional
	public Boolean userLogin(String userName, String password) {
		return userDAO.userLogin(userName, password);
	}

	/**
	 * 获取公司信息
	 * @param orgNo
	 * @return OrganizationDTO
	 */
	@Transactional
	private OrganizationDTO findCompanyNoByOrgNo(Long orgNo) {
		OrganizationDTO orgDTO = new OrganizationDTO();
		Organization org = organizationDAO.findById(orgNo);
		if (org != null) {
			if (org.getOrgType().equals("company")
					|| org.getOrgType().equals("itsop")) {
				orgDTO.setOrgName(org.getOrgName());
				orgDTO.setOrgNo(org.getOrgNo());
				orgDTO.setEmail(org.getEmail());
				orgDTO.setAddress(org.getAddress());
				orgDTO.setOfficePhone(org.getOfficePhone());
				orgDTO.setOrgType(org.getOrgType());
			} else {
				orgDTO = findCompanyNoByOrgNo(org.getParentOrg().getOrgNo());
			}
		}
		return orgDTO;
	}

	/**
	 * 获取当前用户所属的公司编号
	 * @param loginName
	 * @return CompanyDTO
	 */
	@Transactional
	public CompanyDTO findUserCompany(String loginName) {
		CompanyDTO companyDTO = new CompanyDTO();
		User user = userDAO.findUniqueBy("loginName", loginName);
		if (user != null && user.getOrgnization() != null) {
			Organization org = user.getOrgnization();
			//如果用户直接挂在公司或外包公司下，公司信息直接返回
			if("company".equals(org.getOrgType()) || "itsop".equals(org.getOrgType())){
				CompanyDTO.entity2dto(org, companyDTO);
			}else{
				OrganizationDTO orgDTO = findCompanyNoByOrgNo(org.getOrgNo());
				CompanyDTO.entity2dto(orgDTO, companyDTO);
			}
			
		}
		return companyDTO;
	}

	/**
	 * 根据登录名获取对应的分类ID
	 * @param loginName
	 * @param filter
	 * @return Long[]
	 */
	@Transactional
	public Long[] findCategoryNosByLoginName(String loginName, String filter) {
		Long[] categoryNo = null;
		if(StringUtils.hasText(filter)){
			Set<Role> roles = new HashSet<Role>();
			if (StringUtils.hasText(loginName)) {
				User user = userDAO.findUniqueBy("loginName", loginName);
				// 获取用户角色
				if (user != null) {
					for(Role role : user.getRoles()){
		            	if(role.getRoleState()){
		            		roles.add(role);
		            	}
					}
				}
			} else {
				roles.add(roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_ENDUSER));
			}
			if (roles != null) {
				List<String> roleCodes = new ArrayList<String>();
				for (Role role : roles) {
					if(role!=null){
						roleCodes.add(role.getRoleCode()) ;
					}
					
				}
				List<Resource> resources = resourceDAO.findResourcesByResourceCode(filter, roleCodes);
				Set<Long> list = new HashSet<Long>();
				for (Resource resource : resources) {
					if (resource != null && StringUtils.hasText(resource.getResCode())){
						String resNo  = resource.getResCode().replaceAll(filter, "");
						if (!resNo.equals("") && !resNo.equals("View") && isLong(resNo)) {
							list.add(Long.parseLong(resNo));
						}
					}
				}
				categoryNo = (Long[]) list.toArray(new Long[list.size()]);
			}
		}
		return categoryNo;
	}

	/**
	 * 判断字符串是否是整数
	 * 
	 * @param value
	 * @return boolean
	 */
	private static boolean isLong(String value) {
		boolean result = false; 
		try {
			Long.parseLong(value);
			result = true;
		} catch (NumberFormatException e) {
			LOGGER.error(e);
		}
		return result;
	}

	/**
	 * 根据UserId或loginName获取用户详细信息
	 * 
	 * @param userId
	 * @param loginName
	 * @return UserDetailDTO
	 */
	@Transactional
	public UserDetailDTO findUserByUserIdAndLogName(Long userId,
			String loginName) {
		UserDetailDTO userDetailDTO = new UserDetailDTO();
		User user = new User();
		List<String> roleCodeList = new ArrayList<String>();
		if (userId != null && userId != 0) {
			user = userDAO.findById(userId);
		} else if (loginName != null) {
			user = userDAO.findUniqueBy("loginName", loginName);
		}
		if (user != null) {
			UserDetailDTO.entity2dto(user, userDetailDTO);
			if (user.getOrgnization() != null) {
				userDetailDTO.setOrgName(user.getOrgnization().getOrgName());
				userDetailDTO.setOrgNo(user.getOrgnization().getOrgNo());
			}
			if (user.getRoles() != null) {
				Iterator<Role> it = user.getRoles().iterator();
				while (it.hasNext()) {
					Role r = it.next();
					roleCodeList.add(r.getRoleCode());
				}
				userDetailDTO.setRoleCode(roleCodeList);
			}
			// 所属组
			if (user.getBelongsGroup() != null) {
				List<OrganizationDTO> orgs = new ArrayList<OrganizationDTO>();
				for (Organization org : user.getBelongsGroup()) {
					OrganizationDTO orgDTO = new OrganizationDTO();
					OrganizationDTO.entity2dto(org, orgDTO);
					orgs.add(orgDTO);
				}
				userDetailDTO.setBelongsGroups(orgs);
			}
		}

		return userDetailDTO;
	}

	/**
	 * 根据邮件查询用户
	 * @param emails 
	 * @return Map<String, String>
	 */
	public Map<String, String> findUserByEmail(String[] emails) {
		List<User> users = userDAO.findUserByEmail(emails);
		Map<String, String> map = new HashMap<String, String>();
		if (users != null && users.size() > 0) {
			for (User entity : users) {
				map.put(entity.getEmail(), entity.getLoginName());
			}
		}
		return map;
	}

	/**
	 * 获取当前登录用户信息.
	 * @return UserDTO
	 */
	@Transactional
	public UserDTO getCurrentLoginUser() {
		UserDTO userDTO = new UserDTO();
		String loginUserName = appctx.getCurrentLoginName();
		userDTO = getUserDetailByLoginName(loginUserName);
		return userDTO;
	}
	/**
	 * entity to dto 
	 */
	private void entity2dto(User entity,UserDTO dto){
		if (entity.getOrgnization() != null) {// 所属机构
			dto.setOrgName(entity.getOrgnization().getOrgName());
			dto.setOrgNo(entity.getOrgnization().getOrgNo());
		}
		if (entity.getBelongsGroup() != null) {
			Long[] GroupIds = new Long[entity.getBelongsGroup().size()];
			int z = 0;
			for (Organization org : entity.getBelongsGroup()) {
				GroupIds[z] = org.getOrgNo();
				z++;
			}
			dto.setBelongsGroupIds(GroupIds);
		}
		if (entity.getRoles() != null && entity.getRoles().size() > 0) {// 角色
			List<RoleDTO> roles = new ArrayList<RoleDTO>(entity.getRoles()
					.size());
			for (Role rl : entity.getRoles()) {
				RoleDTO roleDTO = new RoleDTO();
				RoleDTO.entity2dto(rl, roleDTO);
				roles.add(roleDTO);
			}
			dto.setUserRoles(roles);
		}
	}

	/**
	 * 根据用户名获取详细信息.
	 * @param loginName
	 * @return UserDTO
	 */
	@Transactional
	public UserDTO getUserDetailByLoginName(String loginName) {
		User entity = userDAO.findUniqueBy("loginName", loginName);
		UserDTO dto = null;
		if (entity != null) {
			dto = new UserDTO();
			UserDTO.entity2dto(entity, dto);
			entity2dto(entity, dto);
		}
		return dto;
	}

	/**
	 * 根据电话、手机号码查询所有用户
	 * @param qdto
	 * @return List<UserDTO>
	 */
	@Transactional
	public List<UserDTO> findUserByNumber(final UserQueryDTO qdto) {
		List<User> list = userDAO.findUserByNumber(qdto);
		List<UserDTO> listDTO = new ArrayList<UserDTO>(list.size());
		for (User entity : list) {
			UserDTO dto = new UserDTO();
			UserDTO.entity2dto(entity, dto);
			if (entity.getOrgnization() != null) {
				dto.setOrgName(entity.getOrgnization().getOrgName());
			}
			listDTO.add(dto);
		}
		return listDTO;
	};

	/**
	 * 免登录
	 * @param requestUserName
	 * @param domainName
	 * @return LDAPAuthenticationSettingDTO
	 */
	@Transactional
	public LDAPAuthenticationSettingDTO autoLogin(String requestUserName,String domainName) {
		boolean result = false;
		LDAPAuthenticationSettingDTO dto = ldapAuthenticationSettingService
				.findLDAPAuthenticationSetting();// 获取LDAP验证配置信息
		if (dto.getEnableAuthentication()) {
			User user = userDAO.findUniqueBy("loginName", requestUserName);
			dto.setAdminName(domainName + "\\" + dto.getAdminName());
			if (ldapService.LDAPAuthenticationSettingConnTest(dto)) {// 判断是否与LDAP连接成功
				LDAPDTO ldapDTO = new LDAPDTO();
				ldapDTO.setLdapType(dto.getLdapType());
				ldapDTO.setLdapURL(dto.getLdapServer());
				ldapDTO.setProt(dto.getProt());
				ldapDTO.setSearchBase(dto.getSearchBase());
				ldapDTO.setAdminName(dto.getAdminName());
				ldapDTO.setAdminPassword(dto.getAdminPassword());
				ldapDTO.setSearchFilter("sAMAccountName=" + requestUserName);
				UserDTO userDTO = ldapService.checkUserNameIsExist(ldapDTO);
				if (userDTO != null
						&& userDTO.getLoginName() != null
						&& userDTO.getDomain().toLowerCase()
								.indexOf(domainName.toLowerCase()) != -1) {// 如果存在则把当前AD用户添加到WSTUO系统中
					if (user == null) {// 判断请求用户是否在WSTUO内存在
						userDTO.setPassword(userDTO.getLoginName());
						userDTO.setUserState(true);
						userDTO.setCompanyNo(1L);// 设置默认所属客户
						userDTO.setOrgNo(1L);// 设置默认属性机构
						Role role = roleDAO.findUniqueBy("roleCode",
								IRoleService.ROLE_ENDUSER);
						if (role != null)
							userDTO.setRoleIds(new Long[] { role.getRoleId() });

						saveUser(userDTO);// 这里是保存AD的用户到WSTUO系统中
						dto.setCommonPassword(userDTO.getPassword());
					}
					if (user != null)
						dto.setCommonPassword(user.getPassword());
					result = true;
				}
			} else {
				result = false;
			}
		}
		if (!result)
			dto = null;
		
		return dto;
	}

	/**
	 * LDAP验证并把用户加入到系统.
	 * @param userName
	 * @param password
	 * @return boolean
	 */
	@Transactional
	public boolean ldapAuthAndUpdate(String userName, String password) {
		boolean result = false;
		LDAPAuthenticationSettingDTO dto = ldapAuthenticationSettingService
				.findLDAPAuthenticationSetting();// 获取LDAP验证配置信息
		if (dto.getEnableAuthentication()) {// 判断是否启用LDAP验证
			if (dto.getLdapType().equals("Microsoft AD(Active Directory)")) {
				dto.setAdminName(userName);// 设置当前输入的用户名作为验证参数
				dto.setAdminPassword(password);// 设置当前输入的密码作为验证参数
			}
			if (dto.getLdapType().equals("OpenLDAP")) {
				dto.setLoginName(userName);
				dto.setPassword(password);
			}

			if (ldapService.LDAPAuthenticationSettingConnTest(dto)) {// 判断是否与LDAP连接成功,如果成功说明当前账号和密码正确
				LDAPDTO ldapDTO = new LDAPDTO();
				ldapDTO.setLdapType(dto.getLdapType());
				ldapDTO.setLdapURL(dto.getLdapServer());
				ldapDTO.setProt(dto.getProt());
				ldapDTO.setSearchBase(dto.getSearchBase());
				ldapDTO.setAdminName(dto.getAdminName());
				ldapDTO.setAdminPassword(dto.getAdminPassword());
				if (dto.getLdapType().equals("OpenLDAP")) {
					ldapDTO.setLoginName(userName);
					ldapDTO.setPassword(password);
				}

				if (ldapDTO.getLdapType().equals(
						"Microsoft AD(Active Directory)")) {
					ldapDTO.setSearchFilter("sAMAccountName=" + userName);
				}
				if (ldapDTO.getLdapType().equals("OpenLDAP")) {
					ldapDTO.setSearchFilter("uid=" + userName);
				}
				UserDTO userDTO = ldapService.checkUserNameIsExist(ldapDTO);// 通过帐号密码得到域用户信息
				if (userDTO != null && userDTO.getLoginName() != null) {// 如果存在则把当前AD用户添加到WSTUO系统中
					User user = userDAO.findUniqueBy("loginName", userName);// 判断当前用户是否在系统中存在
					if (user == null) {// 判断请求用户是否在WSTUO内存在
						if (userDTO.getFirstName() == null) {
							userDTO.setFirstName("");
						}
						userDTO.setPassword(password);
						userDTO.setUserState(true);
						userDTO.setCompanyNo(1L);// 设置默认所属客户
						userDTO.setOrgNo(1L);// 设置默认属性机构
						Role role = roleDAO.findUniqueBy("roleCode",
								IRoleService.ROLE_ENDUSER);
						if (role != null)
							userDTO.setRoleIds(new Long[] { role.getRoleId() });

						saveUser(userDTO);// 这里是保存AD的用户到WSTUO系统中
					} else {
						// 如果密码跟域密码不一致则更新
						if (!user.getPassword().equals(password)) {
							user.setPassword(password);
							try {
								userDAO.merge(user);
							} catch (Exception e) {
								LOGGER.error(e);
							}
						}
					}
					result = true;
				} else {
					result = false;
				}
			} else {
				result = false;
			}
		}

		return result;
	};

	/**
	 * 统计已经使用的技术员数量.
	 * @return int
	 */
	public int countTechnician() {
		return userDAO.countTechnician();
	}

	/**
	 * 判断相关资源权限在当前用户是否可以访问
	 * @param userName
	 * @param res
	 * @return Map<String,Object>
	 */
    @Transactional
	public Map<String, Object> findResAuthByUserName(String userName,String[] res) {

		Map<String, Object> map = new HashMap<String, Object>();
		User user = userDAO.findUniqueBy("loginName", userName);
		if (user != null) {
			// 对机构角色与用户角色进行合并
			Set<Long> roleIds = new HashSet<Long>();
			Set<Role> roleList = user.getRoles();// 用户角色
			for(Role r : roleList){
				if(r.getRoleState()){
					roleIds.add(r.getRoleId());
				}
			}
			if(roleIds.size()==0){
				Role role = roleDAO.findUniqueBy("roleCode",IRoleService.ROLE_ENDUSER);
				roleIds.add(role.getRoleId());  //终端
            }
			List<Resource> resList = resourceDAO.findResourcesByRoleAndResUrl(roleIds, res);
			for (String r1 : res) {
				map.put(r1, false);
			}
			for(Resource entity : resList){
				map.put(entity.getResUrl(), true);
			}
		}
		return map;
	}
	
	/**
     * 判断资源权限在当前用户是否可以访问
     * @param userName
     * @param res
     * @return boolean
     */
    @Transactional
    public boolean isAllowAccessResByCurrentUser(String res){
    	boolean result = false;
    	String loginName = appctx.getCurrentLoginName();
    	User user = userDAO.findUniqueBy("loginName", loginName);
		if (user != null) {
			// 对机构角色与用户角色进行合并
			Set<Long> roleIds = new HashSet<Long>();
			Set<Role> roleList = user.getRoles();// 用户角色
			for(Role r : roleList){
				if(r.getRoleState()){
					roleIds.add(r.getRoleId());
				}
			}
			List<Resource> resList = resourceDAO.findResourcesByRoleAndResUrl(roleIds, new String[]{res});
			if(resList.size()>0){
				result = true;
			}
		}
		return result;
    }

	/**
	 * 根据登录名判断是否存在 findUserByLoginNames
	 * @param loginNames
	 * @return boolean
	 */
	@Transactional
	public Boolean findUserByLoginNames(String[] loginNames) {
	    boolean flag = true;
		if (loginNames != null && loginNames.length > 0) {
			for (String name : loginNames) {
				if (!userDAO.findByUserLoginName(name)) {
				    flag = false;
				}
			}
		}
		return flag;
	}
	public Boolean findUserByLoginName(String loginName) {
	    boolean flag = false;
		if (StringUtils.hasText(loginName) ) {
			User u = userDAO.findUniqueBy("loginName", loginName);
			if (u!= null && u.getLoginName()!=null) {
			    flag = true;
			}
		}
		return flag;
	}

	@Transactional
	public String userActivation(String loginName, String password, String remark) {
		// 根据查找出来的实体为系统插入一个新用户
		String result = "";
		User u = userDAO.findUniqueBy("loginName", loginName);
		if (u == null) {
			User user = new User();
			user.setLoginName(loginName);
			user.setPassword(password);
			user.setRemark(remark);
			user.setUserState(true);
			user.setUserCost((float) 0);
			user.setCompanyNo(1L);
			user.setEmail(loginName);
			List<Role> roles = new ArrayList<Role>();
			Role role = roleDAO.findUniqueBy("roleCode",
					"ROLE_role-common-admin");
			if (role != null) {
				roles.add(role);
			}
			if (roles != null) {
				Set<Role> set = new HashSet<Role>(roles);
				user.setRoles(set);
			}
			Organization org = organizationDAO.findById(182L);
			user.setOrgnization(org);
			user.setCreateTime(new Date());
			user.setLastName("Register");
			userDAO.save(user);
			user.setFirstName("User" + user.getUserId());
			user.setFullName(user.getLastName() + "" + user.getFirstName());
			result = "ActivationSuccess";
		} else {
			result = "AlreadyActivation";
		}
		return result; 
	}

	@Transactional
	public String userKerberos(String loginName, String password) {
		// 根据查找出来的实体为系统插入一个新用户
		String result = null;
		User u = userDAO.findUniqueBy("loginName", loginName);
		if (u == null) {
			User user = new User();
			user.setLoginName(loginName);
			user.setPassword(password);
			user.setRemark("");
			user.setUserState(true);
			user.setUserCost((float) 0);
			user.setCompanyNo(1L);
			List<Role> roles = new ArrayList<Role>();
			Role role = roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_ENDUSER);
			if (role != null) {
				roles.add(role);
			}
			if (roles != null) {
				Set<Role> set = new HashSet<Role>(roles);
				user.setRoles(set);
			}
			Organization org = organizationDAO.findById(1L);
			user.setOrgnization(org);
			user.setCreateTime(new Date());
			user.setFirstName("User" + user.getUserId());
			user.setLastName("Kerberos");
			userDAO.save(user);
			result = "KerberosSuccess";
		} else {
			// 如果密码跟域密码不一致则更新
			if (!u.getPassword().equals(sha.Encryption(password))) {
				u.setPassword(password);
				try {
					userDAO.merge(u);
				} catch (Exception e) {
					LOGGER.error(e);
				}
			}
			result = "AlreadyKerberos";
		}
		return result;
	}

	@Transactional
	public String updateOnLineRegisterStatus(String dataFlag, String loginName) {
	    String result = "";
		// 根据查找出来的用户
		User u = userDAO.findUniqueBy("loginName", loginName);
		if (u != null) {
		    u.setUserState("1".equals(dataFlag));
			userDAO.merge(u);
			result = "UpdateSuccess";
		} else {
		    result = "UpdateErrror";
		}
		return result;
	}

	/**
	 * 根据打过来的电话去查询用户
	 * @param dto
	 * @return UserDTO
	 */
	@Transactional
	public UserDTO updateUserByPhone(UserDTO dto) {
		User user = new User();
		if (dto != null) {
			if (dto.getMoblie() == null) {
				user = userDAO.findUniqueBy("phone", dto.getPhone());
			} else {
				user = userDAO.findUniqueBy("moblie", dto.getMoblie());
			}
		}
		if (user != null) {
			UserDTO.entity2dto(user, dto);
		} else {
			dto = null;
		}
		return dto;
	}

	/**
	 * 根据用户名称修改用户手机号码
	 */
	@Transactional
	public boolean findUserUpdatePhone(UserDTO dto) {
	    boolean result = false;
		User user = userDAO.findUniqueBy("loginName", dto.getLoginName());
		if (user != null) {
			if (dto.getMoblie() == null) {
				user.setPhone(dto.getPhone());
			} else {
				user.setMoblie(dto.getMoblie());
			}
			userDAO.merge(user);
			result = true;
		} else {
		    result = false;
		}
		return result;
	}

	@Transactional
	public UserDTO saveUserByPhone(UserDTO dto) {
		//int names = (int) (Math.random() * 10000000);
		//String loginNames = String.valueOf(names);
		User u = userDAO.findUniqueBy("loginName", dto.getPhone());
		if (u == null) {
			User user = new User();
			user.setLoginName(dto.getPhone());
			if(StringUtils.hasText(dto.getPassword()))
				user.setPassword(dto.getPassword());
			else
				user.setPassword(dto.getPhone());
			user.setRemark(dto.getRemark());
			user.setUserState(true);
			user.setUserCost((float) 0);
			user.setCompanyNo(1L);
			if (StringUtils.hasText(dto.getPhone())) {
				user.setMoblie(dto.getPhone());
			} 

			List<Role> roles = new ArrayList<Role>();
			Role role = roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_ENDUSER);
			if (role != null) {
				roles.add(role);
			}
			if (roles != null) {
				Set<Role> set = new HashSet<Role>(roles);
				user.setRoles(set);
			}
			Organization org = organizationDAO.findById(dto.getOrgNo());
			user.setOrgnization(org);
			user.setCreateTime(new Date());
			if(StringUtils.hasText(dto.getFirstName())){
				user.setFirstName(dto.getFirstName());
				user.setLastName(dto.getLastName());
			}else{
				user.setFirstName(dto.getPhone());
			}
			user.setFullName("");
			userDAO.save(user);
			UserDTO.entity2dto(user, dto);
		} else {
			u.setMoblie(dto.getPhone());
			userDAO.merge(u);
			UserDTO.entity2dto(u, dto);
		}
		return dto;
	}

	// 根据id查询
	@Transactional
	public UserDTO findUserById(UserDTO dto) {
		User user = userDAO.findById(dto.getUserId());
		if (user != null) {
			UserDTO.entity2dto(user, dto);
		}
		return dto;
	}

	@Transactional
	public UserDTO setUserRandomId(UserDTO dto) {
		if (dto != null) {
			User user = new User();
			if (dto.getUserId()!=null&&dto.getUserId() != 0) {
				user = userDAO.findById(dto.getUserId());
			} else {
				user = userDAO.findUniqueBy("loginName", dto.getLoginName());
			}
			if (user != null) {
				if (user.getRandomId() == null) {
					UUID uuid = UUID.randomUUID();
					user.setRandomId(uuid.toString());
					userDAO.merge(user);
				}
				UserDTO.entity2dto(user, dto);
			}
		}
		return dto;
	}

	@Transactional
	public UserDTO findUserByRandomNum(UserDTO dto) {
		User user = userDAO.findUniqueBy("randomId", dto.getRandomId());
		if (user != null) {
			UserDTO.entity2dto(user, dto);
		} else {
			dto = null;
		}
		return dto;
	}

	/**
	 * 根据用户ID判断用户是否为非终端用户
	 * 
	 * @param loginName
	 * @return true 为非终端用户  false 为终端用户
	 */
	@Transactional
	public boolean checkNonTerminal(String loginName) {
		
		User user = userDAO.findUniqueBy("loginName", loginName);
		if(user!=null){
			return userDAO.isTc(user.getRoles());
		}else{
			return false;
		}
	}
	
	/**
	 * 检验用户是否存在.
	 */
	@Transactional
	public boolean vaildateUserByIds(String[] userNames){
		boolean result = true;
		for (String userName : userNames) {
			if (StringUtils.hasText(userName) && findUserByName(userName) == null) {
				result = false;
				break;
			}
		}
		return result;
	}
	/**
	   * 查询我的所属技术组
	   * @param loginName
	   * @return
	   */
	@Transactional
	public Long[] findMyRelatedTechnologyGroup(String loginName){
		Set<Long> groupIds = new HashSet<Long>();// 唯一集合
		User entity = userDAO.findUniqueBy("loginName", loginName);
		if(entity!=null && entity.getBelongsGroup()!=null){
			for (Organization org : entity.getBelongsGroup()) {
				groupIds.add(org.getOrgNo());
			}
			Long[] toArray = groupIds.toArray(new Long[groupIds.size()]);
			return toArray;
		}else{
			return null;
		}
		
	}
	
	/**
	 * 根据登录名查找用户
	 * 
	 * @param loginNames
	 * @return List<User>
	 */
	public List<User> findUsersByname(String loginNames) {
		List<User> users = new ArrayList<User>();
		if (loginNames != null) {
			String[] roles = loginNames.split(";");
			for (String str : roles) {
				User user = userDAO.findUniqueBy("loginName", str);
				users.add(user);
			}
		}
		return users;
	}
	

	/**
	 * 根据登录名处理对应的客户端绑定与解除绑定；
	 * userName 为null ，clientId不为null，那么就是解绑所有包含这个ClientId的用户；
	 * userName 不为null ，clientId为null，那么解绑该用户；
	 * userName 不为null ，clientId不为null，那么就是绑定；
	 * @param loginNames
	 * @param cilentId
	 */
	@Transactional
	public String pushUserBind(String userName,String clientId) {
		unbindUser(clientId);
		if (userName != null) {
			User user = userDAO.findUniqueBy("loginName", userName);
			if (user != null) {
				UserInfoClient client = user.getUserInfoClient();
				if (client == null) {
					client = new UserInfoClient();
				}
				client.setMoblieClientId(clientId);
				user.setUserInfoClient(client);
				userDAO.merge(user);
			}
		}
		
		return clientId;
	}
	/**
	 * 解除该clientId与其他用户的绑定
	 * @param clientId
	 */
	@Transactional
	public void unbindUser(String clientId) {
		if (clientId != null) {
			List<User> users = userDAO.findByUserClientId( clientId );
			if (users != null &&users.size() > 0) {
				for (User u : users) {
					UserInfoClient client = u.getUserInfoClient();
					if (client == null) {
						client = new UserInfoClient();
					}
					client.setMoblieClientId( null );
					u.setUserInfoClient( client );//
				}
				userDAO.mergeAll(users);
			}
		}
	}
	
	/**消息数量修改
	 * @return messageCount
	 */
	@Transactional
	public int pushCount(String userName,int count) {
		if (userName != null) {
			User user = userDAO.findUniqueBy("loginName", userName);
			if (user != null) {
				UserInfoClient client = user.getUserInfoClient();
				if (client == null) {
					client = new UserInfoClient();
				}
				if (count == -1) {
					count = client.getMessageCount() + 1;
				}
				if (count == -2) {
					count = client.getMessageCount()- 1;
				}
				if (count < 0) {
					count = 0;
				}
				client.setMessageCount( count );
				userDAO.merge(user);
			}
		}
		return count;
	}
	

	/**
	 * 获取变量指派人
	 * @param assignee 指派人
	 * @param variablesAssigneeType 变量类型
	 * @param createdByNo 请求人
	 * @param technicianNo  指派技术员
	 * @param variablesAssigneeGroupNo  指派组
	 * @return User
	 */
	public User setVariablesAssignee(User assignee ,String variablesAssigneeType,Long createdByNo,Long technicianNo,Long variablesAssigneeGroupNo){
		//请求人
		if ("creator".equals(variablesAssigneeType)){
			if(createdByNo!=null){
				assignee = userDAO.findById(createdByNo);
			}
		//指派的技术员
		} else if ("technician".equals(variablesAssigneeType)) {
			if(technicianNo!=null){
				assignee = userDAO.findById(technicianNo);
			}
		//请求人所属机构的负责人(1,2,3,4)
		} else if (variablesAssigneeType.indexOf("leader_") > -1) {
			String[] assignTypes = variablesAssigneeType.split("_");
			assignee =  organizationService.findOrganizationOwnerByUser(createdByNo,Long.parseLong(assignTypes[1]));
		//指派组的负责人
		}else if ("groupHead".equals(variablesAssigneeType) && variablesAssigneeGroupNo!=null) {
			assignee = organizationDAO.findById(variablesAssigneeGroupNo).getPersonInCharge();
		}
		return assignee;
	}

	@Override
	@Transactional
	public int changeEndUserStyle(UserDTO dto) {
		int bl=1;
		User user = userDAO.findById(dto.getUserId());
		user.setEndUserStyle(dto.getEndUserStyle());
		userDAO.merge(user);
		appctx.setAttribute(SessionName.ENDUSERSTYLE.getName(), user.getEndUserStyle());
		return bl;
	}
	
	

	
	/**
	 * 免登录用户新增
	 * @param loginName 验证人
	 */
	@Transactional
	public void userSsoAdd(String loginName,String password) {
		// 根据查找出来的实体为系统插入一个新用户
		User user = new User();
		user.setLoginName(loginName);
		user.setPassword(password);
		user.setRemark("");
		user.setUserState(true);
		user.setUserCost((float) 0);
		user.setCompanyNo(1L);
		List<Role> roles = new ArrayList<Role>();
		Role role = roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_ENDUSER);
		if (role != null) {
			roles.add(role);
		}
		if (roles != null) {
			Set<Role> set = new HashSet<Role>(roles);
			user.setRoles(set);
		}
		Organization org = organizationDAO.findById(1L);
		user.setOrgnization(org);
		user.setCreateTime(new Date());
		user.setFirstName(loginName);
		user.setLastName("");
		userDAO.save(user);
	}
	/**
	 * 同步用户信息
	 * @param btuDto
	 */
	@Transactional
	public void synchronizeBtUser(SSOUserDTO btuDto){
		User btuser = userDAO.findUniqueBy("loginName",btuDto.getLogin());
		if(btuser!=null){//如果存在用户，则修改用户信息
			btuser.setMoblie(btuDto.getPhone());
			btuser.setEmail(btuDto.getEmail());
			btuser.setFirstName("");
			btuser.setLastName(btuDto.getName());
			btuser.setFullName("");
			userDAO.merge(btuser);
		}else{//如果没有用户，则新增
			User user = new User();
			user.setLoginName(btuDto.getLogin());
			user.setPassword(btuDto.getPassword());
			user.setRemark("");
			user.setUserState(true);
			user.setUserCost((float) 0);
			user.setCompanyNo(1L);
			List<Role> roles = new ArrayList<Role>();
			Role role = roleDAO.findUniqueBy("roleCode", IRoleService.ROLE_ENDUSER);
			if (role != null) {
				roles.add(role);
			}
			if (roles != null) {
				Set<Role> set = new HashSet<Role>(roles);
				user.setRoles(set);
			}
			Organization org = organizationDAO.findById(1L);
			user.setOrgnization(org);
			user.setCreateTime(new Date());
			user.setFirstName("");
			user.setLastName(btuDto.getName());
			user.setFullName("");
			user.setMoblie(btuDto.getPhone());
			user.setEmail(btuDto.getEmail());
			userDAO.save(user);
		}
		
	}
	/**
	 * 创建租户用户
	 */
	@Transactional
	public void createTenantUser(UserDTO userDTO){
		if(userDTO.getPassword()==null){
			userDTO.setPassword("itsmbest");
		}
		userDTO.setUserState(true);
		userDTO.setCompanyNo(1L);// 设置默认所属客户
		userDTO.setOrgNo(1L);// 设置默认属性机构
		userDTO.setEmail(userDTO.getLoginName());
		Role role = roleDAO.findUniqueBy("roleCode",IRoleService.ROLE_SYSADMIN);
		if (role != null)
			userDTO.setRoleIds(new Long[] { role.getRoleId() });
		saveUser(userDTO);
	}
}
